package y.q.h.util;

import org.apache.log4j.Logger;

import javax.activation.MimetypesFileTypeMap;
import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Tools {
	 public static  String httpsRequest(String requestUrl,String outputStr){
	        String result= "";
	        try {
	        	TrustManager[] tm = {new MyX509TrustManager()};
	            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
	            sslContext.init(null, tm, new java.security.SecureRandom());
	            SSLSocketFactory ssf = sslContext.getSocketFactory();
	            URL url = new URL(requestUrl);
	            //通过远程url连接对象打开连接//设置连接请求方式
	            HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
	           conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");	    
	            //设置连接方式：post
	            conn.setRequestMethod("POST");
	            //设置连接主机服务器超时时间：10000毫秒
	            conn.setDoOutput(true);
	            //默认值为：true，当前向远程服务器读取数据时，设置为true，该参数可有可无
	            conn.setDoInput(true);
	            //设置传入参数的格式：请求参数应该时json的形式。
	              
	            conn.setSSLSocketFactory(ssf);
	            if (null != outputStr){
	                //通过连接对象获取一个输出流 //通过输出流对象将参数写出去/传输出去，它是通过字节数组写出的
	                OutputStream outputStream = conn.getOutputStream();
	                outputStream.write(outputStr.getBytes("UTF-8"));
	                outputStream.close();
	            }
	            //通过连接对象获取一个输入流，向远程读取// 对输入流对象进行包装charset根据工作项目组的要求来设置
	            InputStream inputStream = conn.getInputStream();
	            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
	            String temp = null;
	            //循环遍历一行一行读取数据
	            while ((temp = bufferedReader.readLine()) != null){
	            	result=result+temp;
	            }
	            bufferedReader.close();
	            inputStream.close();
	            inputStream = null;
	            conn.disconnect();
	            
	            logger.info("param="+outputStr+" url="+requestUrl+" result="+result);
	        }catch (Exception e){
	        	 logger.info("param="+outputStr+" url="+requestUrl+" result="+result);
	        	 logger.error("https回传报错：", e);
	         
	        }
	        return result;
	    }
	
	  private static final int  BUFFER_SIZE =  1024;
	//判断是Int
		 public static boolean isInt(String name) {
			 try {
				Integer.parseInt(name);
				return true;
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				return false;
			}
		 }
		//判断是Double
			 public static boolean isDouble(String name) {
				 try {
					 Double.parseDouble(name);
					return true;
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					return false;
				}
			 }
		//判断是日期格式yyyy-MM-dd HH:mm:ss
		public static boolean isLegalDate(int length, String sDate,String format) {
		        int legalLen = length;
		        if ((sDate == null) || (sDate.length() != legalLen)) {
		            return false;
		        }
		        DateFormat formatter = new SimpleDateFormat(format);
		        try {
		            Date date = formatter.parse(sDate);
		            return sDate.equals(formatter.format(date));
		        } catch (Exception e) {
		            return false;
		        }
		    }
	  public static String getIpAddr(HttpServletRequest request) {
	        String ip = request.getHeader("x-forwarded-for"); 
	        System.out.println("x-forwarded-for ip: " + ip);
	        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {  
	            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
	            if( ip.indexOf(",")!=-1 ){
	                ip = ip.split(",")[0];
	            }
	        }  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getHeader("Proxy-Client-IP");  
	            System.out.println("Proxy-Client-IP ip: " + ip);
	        }  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getHeader("WL-Proxy-Client-IP");  
	            System.out.println("WL-Proxy-Client-IP ip: " + ip);
	        }  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getHeader("HTTP_CLIENT_IP");  
	            System.out.println("HTTP_CLIENT_IP ip: " + ip);
	        }  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
	            System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
	        }  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getHeader("X-Real-IP");  
	            System.out.println("X-Real-IP ip: " + ip);
	        }  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getRemoteAddr();  
	            System.out.println("getRemoteAddr ip: " + ip);
	        } 
	        System.out.println("获取客户端ip: " + ip);
	        return ip;  
	    }
	  
	  
	  public static String downloadPicture(String urlList,String path) {
		  String str="1";
	        URL url = null;
	        try {
	            url = new URL(urlList);
	            DataInputStream dataInputStream = new DataInputStream(url.openStream());
	 
	            FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
	            ByteArrayOutputStream output = new ByteArrayOutputStream();
	 
	            byte[] buffer = new byte[1024];
	            int length;
	 
	            while ((length = dataInputStream.read(buffer)) > 0) {
	                output.write(buffer, 0, length);
	            }
	            fileOutputStream.write(output.toByteArray());
	            dataInputStream.close();
	            fileOutputStream.close();
	        } catch (Exception e) {
	        	str=null;
	           e.printStackTrace();
	        }
			return str;
	    }

	  
	  
	  public static String toZip1(File[] srcFiles ,String path,String fileName)throws RuntimeException, IOException {	
		File file=new File(path);
		  if(file.exists()){
			  file.mkdirs();
			 
		  }
		  FileOutputStream fileOutputStream=new FileOutputStream(path+fileName);
			        long start = System.currentTimeMillis();		
			        ZipOutputStream zos = null ;		
			        try {		
			            zos = new ZipOutputStream(fileOutputStream);		
			            for (File srcFile : srcFiles) {		
			                byte[] buf = new byte[BUFFER_SIZE];		
			                zos.putNextEntry(new ZipEntry(srcFile.getName()));		
			                int len;		
			                FileInputStream in = new FileInputStream(srcFile);		
			                while ((len = in.read(buf)) != -1){		
			                    zos.write(buf, 0, len);	
			                }
			                zos.closeEntry();		
			                in.close();
			            }		
			            long end = System.currentTimeMillis();		
			            System.out.println("压缩完成，耗时：" + (end - start) +" ms");
			            for (File srcFile : srcFiles) {		
				              srcFile.delete();
				            }		
			        } catch (Exception e) {		
			          e.printStackTrace();
			        }finally{
			            if(zos != null){	
			                try {	
			                    zos.close();
			                } catch (IOException e) {
			                   e.printStackTrace();
			                }
			            }
			        }
			      
					return path+fileName;
			    }
	  
	  
	public static void toZip(List<File> srcFiles ,String path,HttpServletResponse response,String fileName)throws RuntimeException, IOException {	
		FileOutputStream fileOutputStream=new FileOutputStream(path);
		        long start = System.currentTimeMillis();		
		        ZipOutputStream zos = null ;		
		        try {		
		            zos = new ZipOutputStream(fileOutputStream);		
		            for (File srcFile : srcFiles) {		
		                byte[] buf = new byte[BUFFER_SIZE];		
		                zos.putNextEntry(new ZipEntry(srcFile.getName()));		
		                int len;		
		                FileInputStream in = new FileInputStream(srcFile);		
		                while ((len = in.read(buf)) != -1){		
		                    zos.write(buf, 0, len);	
		                }
		                zos.closeEntry();		
		                in.close();
		            }		
		            long end = System.currentTimeMillis();		
		            System.out.println("压缩完成，耗时：" + (end - start) +" ms");
		            for (File srcFile : srcFiles) {		
			              srcFile.delete();
			            }		
		        } catch (Exception e) {		
		          e.printStackTrace();
		        }finally{
		            if(zos != null){	
		                try {	
		                    zos.close();
		                } catch (IOException e) {
		                   e.printStackTrace();
		                }
		            }
		        }
		        	
		        Tools.downfile(path, fileName, response);
		    }
	//下载文件
	public static void downfile(String path,String filename,HttpServletResponse response) throws IOException{
		System.err.println(filename+"==============");
			response.setContentType("application/x-msdownload");
		     response.addHeader("Content-Disposition","attachment;fileName="+new String(filename.getBytes(),"iso8859-1"));
		     OutputStream os = response.getOutputStream(); 
		    FileInputStream fis = new FileInputStream(path); 
		    try{
		        
		     	BufferedInputStream bufferedInputStream=new BufferedInputStream(fis);
				BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(os);
				 byte[] buffer = new byte[4096];
			       int count = 0;
				while ((count=bufferedInputStream.read(buffer, 0, buffer.length))>0) {
					bufferedOutputStream.write(buffer, 0, count);
				}
				bufferedInputStream.close();
				bufferedOutputStream.flush();
				bufferedOutputStream.close();
				os.close();
				fis.close();
		    }catch(Exception e){
		         e.printStackTrace();
		     }
		    File file=new File(path);
		    file.delete();
	}
	//下载
	public static void down(HttpServletResponse response,String filename,String contents) throws IOException{
		String regex = "[\u4e00-\u9fff]";
		int countnum = (" " + contents + " ").split (regex).length - 1; 
		int countss=contents.length()+countnum*2;
		response.setContentType("application/x-msdownload");
		response.addHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes("utf-8"),"iso8859-1")+".csv");
		OutputStream outputStream=response.getOutputStream();
		ByteArrayInputStream arrayInputStream=new ByteArrayInputStream(contents.getBytes(), 0, countss);
		
		BufferedInputStream bufferedInputStream=new BufferedInputStream(arrayInputStream);
		BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(outputStream);
		 byte[] buffer = new byte[4096];
	       int count = 0;
		while ((count=bufferedInputStream.read(buffer, 0, buffer.length))>0) {
			bufferedOutputStream.write(buffer, 0, count);
		}
		bufferedInputStream.close();
		bufferedOutputStream.flush();
		bufferedOutputStream.close();
		arrayInputStream.close();
		outputStream.close();
	}
	
	public static final Integer pageSize=15;
	public static  String getPagerNormal(Integer total, int pagesize, int pagenum,String pageurl,String info) {
		int count = (total / pagesize);
		if (total % pagesize > 0) {
			count++;
		}
		if(pageurl.indexOf("?")>-1){
			pageurl = pageurl + "&";
		}else{
			pageurl = pageurl + "?";
		}
		StringBuffer buf = new StringBuffer();
		
		if (pagenum == 1) {
			buf.append("<SPAN style='color:#CCCCCC'>【首页】</SPAN><SPAN style='color:#CCCCCC'>【上一页】</SPAN>&nbsp;&nbsp;");
		} else {
			buf.append("【<a href='" + pageurl + "pagenum=1'>首页</a>】【<a href='" + pageurl + "pagenum=" + (pagenum - 1)
					+ "' >上一页</a>】");
		}
		int bound1 = ((pagenum - 2) <= 0) ? 1 : (pagenum - 2);
		int bound2 = ((pagenum + 2) >= count) ? count : (pagenum + 2);
		for (int i = bound1; i <= bound2; i++) {
			if (i == pagenum) {
				buf.append("<SPAN style='color:#FF0000'>" + i
						+ "</SPAN>&nbsp;&nbsp;");
			} else {
				buf.append("<a href='" + pageurl + "pagenum=" + i + "'>" + i
						+ "</a>&nbsp;&nbsp;");
			}
		}
		if (bound2 < count) {
			buf.append("<SPAN>...</SPAN>");
		}
		if (pagenum == count||count==0) {
			buf.append("<SPAN style='color:#CCCCCC'>【下一页】</SPAN><SPAN style='color:#CCCCCC'>【尾页】</SPAN>");
		} else {
			buf.append("【<a href='" + pageurl + "pagenum=" + (pagenum + 1)
					+ "'>下一页</a>】【<a href='" + pageurl + "pagenum=" + count
					+ "'>尾页</a>】");
		}
		buf.append("共"+total+"条&nbsp;&nbsp;");
		buf.append(count +"页&nbsp;&nbsp;");
		return buf.toString();
	}
	

	
	static Logger logger=Logger.getLogger(Tools.class);
public static  String sendPost(String urlStr,String param,String ContentType){
	PrintWriter printWriter = null;
	BufferedReader reader = null;
	String result="";
		try {
			URL url=new URL(urlStr);
			HttpURLConnection conn=	(HttpURLConnection) url.openConnection();
			if(ContentType==null){
				conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			}else{
				conn.setRequestProperty("Content-Type", "application/json");
			}
			conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Shuame)");
			conn.setRequestMethod("POST");
			conn.setDoInput(true);
			conn.setDoOutput(true);
			 printWriter=new PrintWriter(conn.getOutputStream());
			printWriter.print(param);
			printWriter.flush();
			printWriter.close();		
			 reader=new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String str=null;
			
			while((str=reader.readLine())!=null){
				result+=str+"";
			}			
			reader.close();		
			
		
		} catch (Exception e) {
			
			logger.error("回调错误：", e);
		} finally{
            try{
                if(printWriter!=null){
                	printWriter.close();
                }
                if(reader!=null){
                	reader.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
		logger.info("url:"+urlStr+" param:"+param+" result:"+result);
		return result;
	}
	
	
	public static String encryption(String plainText) {
        String re_md5 = new String();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
 
            int i;
 
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
 
            re_md5 = buf.toString();
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return re_md5;
    }
	
	
	public static String getValue(String path,String key){
		String value = null;
		try {
			File file=new File(path+"WEB-INF/classes/config.properties");
			InputStreamReader inStream=new InputStreamReader(new FileInputStream(file));
			Properties properties=new Properties();
			properties.load(inStream);
			value = properties.getProperty(key);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return value;
	}
	 public static String sendPostKey(String url, String param) {
		 
	        PrintWriter out = null;
	        BufferedReader in = null;
	        String result = "";
	        try {
	            URL realUrl = new URL(url);
	            // 打开和URL之间的连接
	            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
	            // 设置通用的请求属性
	            conn.setRequestProperty("accept", "*/*");
	            conn.setRequestProperty("connection", "Keep-Alive");
	            conn.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            // 发送POST请求必须设置如下两行
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	            // 获取URLConnection对象对应的输出流
	            out = new PrintWriter(conn.getOutputStream());
	            // 发送请求参数
	            out.print(param);
	            // flush输出流的缓冲
	            out.flush();
	            // 定义BufferedReader输入流来读取URL的响应
	          //  in = 		new BufferedReader(new InputStreamReader(conn.getResponseCode()==HttpURLConnection.HTTP_OK?conn.getInputStream():conn.getErrorStream(),"utf-8"));
	            in = new BufferedReader(
	                    new InputStreamReader(conn.getInputStream(),"utf-8"));
	            String line;
	            while ((line = in.readLine()) != null) {
	            	
	                result += line;
	            }
	            
		        logger.info("param:"+param+"   URL:"+url+"   result:"+result);

	        } catch (Exception e) {
	          
	            logger.info("发送 POST 请求出现异常！"+e.getMessage());
	            logger.info("param:"+param+"   URL:"+url+"   result:"+result);
	        }
	        //使用finally块来关闭输出流、输入流
	        finally{
	            try{
	                if(out!=null){
	                    out.close();
	                }
	                if(in!=null){
	                    in.close();
	                }
	            }
	            catch(IOException ex){
	                ex.printStackTrace();
	            }
	        }
	        return result;
	    }
	
/**
 * 获取三个小数
 * @param d 一个double类型的数值
 * @return 返回三个小数
 */
public static double getThreeDecimal(double d) {
	//将一个double类型的数值转换为BigDecimal类型，并赋值给变量b。BigDecimal类型可以保留小数点后的位数，而double类型在进行浮点数运算时可能会有精度问题。
    BigDecimal b = new BigDecimal(d);
	//这个函数将参数b四舍五入保留3位小数，并将结果转换为double类型返回。其中BigDecimal.ROUND_HALF_UP是四舍五入的模式，表示遇到5进1。
    return d = b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
}

	
	 public static String getImgStr(String path,String imgFile,String filename){
         InputStream in = null;
         byte[] data = null;
         //读取图片字节数组
	       try {
	    	  
			   	int ex=imgFile.lastIndexOf(".");
			   		BufferedImage bufferedImage;
				        bufferedImage = ImageIO.read(new File(path+imgFile));
				        BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
				        bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
				        newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
				        imgFile=filename;
				        ImageIO.write(newBufferedImage, "jpg", new File(path+imgFile));
				        in = new FileInputStream(path+imgFile);        
			            data = new byte[in.available()];
			             in.read(data);
			            in.close();
				        
			   	
	        } catch (IOException e) 
	         {
	            e.printStackTrace();
	        }
         return path+filename;
    }
	public static String queryYear(int year,String startTime){
		SimpleDateFormat format =  new  SimpleDateFormat("yyyy-MM-dd" );
        Calendar c = Calendar.getInstance();
        c.setTime( new  Date());
        c.add(Calendar.YEAR, year );
        Date y = c.getTime();
        String years = format.format(y);
        System.err.println(years.compareTo(startTime));
        if(years.compareTo(startTime)>0){
        	return years;
        }else{
        	return startTime;
        }
        
	}
	public static String getStringRandom(int length) {
        String val = "";
        Random random = new Random();
        
        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {
            
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;}
	 public static String formUpload(String urlStr, Map<String, Object> textMap,
				Map<String, String> fileMap,String contentType) {
			String res = "";
			HttpURLConnection conn = null;
			// boundary就是request头和上传文件内容的分隔符
			String BOUNDARY = "------WebKitFormBoundary"+getStringRandom(16); 
			try {
				URL url = new URL(urlStr);
				conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(5000);
				conn.setReadTimeout(60000);
				conn.setDoOutput(true);
				conn.setDoInput(true);
				conn.setUseCaches(false);
				conn.setRequestMethod("POST");
				conn.setRequestProperty("Connection", "Keep-Alive");
				conn.setRequestProperty("User-Agent",
						"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
				conn.setRequestProperty("Content-Type",
						"multipart/form-data; boundary=" + BOUNDARY);
				
				
				OutputStream out = new DataOutputStream(conn.getOutputStream());
				// text
				if (textMap != null) {
					StringBuffer strBuf = new StringBuffer();
					Iterator iter = textMap.entrySet().iterator();
					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						String inputName = (String) entry.getKey();
						String inputValue = (String) entry.getValue();
						if (inputValue == null) {
							continue;
						}
						strBuf.append("\r\n").append("--").append(BOUNDARY)
								.append("\r\n");
						strBuf.append("Content-Disposition: form-data; name=\""
								+ inputName + "\"\r\n\r\n");
						strBuf.append(inputValue);
						System.out.println(inputName+","+inputValue);
					}
					out.write(strBuf.toString().getBytes());
				}
				// file
				if (fileMap != null) {
					Iterator iter = fileMap.entrySet().iterator();
					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						String inputName = (String) entry.getKey();
						String inputValue = (String) entry.getValue();
						if (inputValue == null) {
							continue;
						}
						System.err.println(inputValue);
						File file = new File(inputValue);
						String filename = file.getName();
						
						//没有传入文件类型，同时根据文件获取不到类型，默认采用application/octet-stream
						contentType = new MimetypesFileTypeMap().getContentType(file);
						//contentType非空采用filename匹配默认的图片类型
						if(!"".equals(contentType)){
							if (filename.endsWith(".png")) {
								contentType = "image/png"; 
							}else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
								contentType = "image/jpeg";
							}else if (filename.endsWith(".gif")) {
								contentType = "image/gif";
							}else if (filename.endsWith(".ico")) {
								contentType = "image/image/x-icon";
							}
						}
						StringBuffer strBuf = new StringBuffer();
						strBuf.append("\r\n").append("--").append(BOUNDARY)
								.append("\r\n");
						strBuf.append("Content-Disposition: form-data; name=\""
								+ inputName + "\"; filename=\"" + filename
								+ "\"\r\n");
					
						
						strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
						System.out.println(strBuf.toString());
						out.write(strBuf.toString().getBytes());
						DataInputStream in = new DataInputStream(
								new FileInputStream(file));
						int bytes = 0;
						byte[] bufferOut = new byte[1024];
						while ((bytes = in.read(bufferOut)) != -1) {
							out.write(bufferOut, 0, bytes);
						}
						in.close();
					}
				}
				byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
				System.out.println(new String(endData));
				out.write(endData);
				out.flush();
				out.close();
				// 读取返回数据
				StringBuffer strBuf = new StringBuffer();
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				String line = null;
				while ((line = reader.readLine()) != null) {
					strBuf.append(line).append("\n");
				}
				res = strBuf.toString();
			
				reader.close();
				reader = null;
				logger.info("url:"+urlStr+" result:"+res);
			} catch (Exception e) {
				logger.error("url:"+urlStr,e);
				e.printStackTrace();
			} finally {
				if (conn != null) {
					conn.disconnect();
					conn = null;
				}
			}
			return res;
		}
	 
	 /**
	  * 计算天数
	  * @param before 开始时间
	  * @param after 结束时间
	  * @return
	  */
	 public static long getDays(Date before, Date after) {
			long beforeTime = before.getTime();
			long afterTime = after.getTime();
			return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);

	 }
}
